package leetcode;

import leetcode.vo.ListNode;

public class RemoveNthFromEnd {

    public static void main(String[] args) {
        RemoveNthFromEnd e = new RemoveNthFromEnd();

        ListNode n1 = new ListNode();
        n1.val = 2;
        ListNode n2 = new ListNode();
        n2.val = 3;
        ListNode n3 = new ListNode();
        n3.val = 5;
        n1.next = n2;
        n2.next = n3;

        ListNode n11 = new ListNode();
        n11.val = 3;
        ListNode n12 = new ListNode();
        n12.val = 6;
        ListNode n13 = new ListNode();
        n13.val = 9;
        n3.next = n13;
        n11.next = n12;
        n12.next = n13;

        ListNode listNode = e.removeNthFromEnd(n1, 3);
        System.out.println(listNode);
    }

    // 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; i++) {
            first = first.next;
        }
        while (first != null){
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        ListNode ans = dummy.next;
        return ans;
    }

}
